library ( ncdf )
source ( paste ( app_root, "cgi-lib/R/ep.io.R", sep="/" ) );
load ( paste ( app_root, "cgi-lib/R/clustering_comparison.RData", sep="/") );

hier.flat.comparison <- function ( tree.clustering.cdf, flat.clustering.cdf, look.ahead, scoring.function, cte, output.cdf ) {
# read in the data
  tree.clustering.nc = open.ncdf ( tree.clustering.cdf )
  flat.clustering.nc = open.ncdf ( flat.clustering.cdf )

  tree.clustering.hclust =  list (
    merge = get.var.ncdf ( tree.clustering.nc, 'merge' ),
    order = get.var.ncdf ( tree.clustering.nc, 'order' ),
    height = get.var.ncdf ( tree.clustering.nc, 'height' ) );
  class ( tree.clustering.hclust ) = "hclust";

  flat.clustering = get.var.ncdf ( flat.clustering.nc, 'correspondence' );

# run the comparison
  comparison <- comparison.tree.flat ( tree.clustering.hclust, flat.clustering, look.ahead, scoring.function, cte );

# write output
  x  <- dim.def.ncdf ( "x",  "", 1:nrow(comparison$new.tree) )
  y  <- dim.def.ncdf ( "y",  "", 1:ncol(comparison$new.tree) )
  ox <- dim.def.ncdf ( "ox", "", 1:nrow(comparison$ordered.weight.matrix) )
  oy <- dim.def.ncdf ( "oy", "", 1:ncol(comparison$ordered.weight.matrix) )

  var.new.tree              <- var.def.ncdf ("new_tree",              "", list(x,y),   NA )
  var.ordered.weight.matrix <- var.def.ncdf ("ordered_weight_matrix", "", list(ox,oy), NA )
  var.leaves.order          <- var.def.ncdf ("leaves_order",          "", list(x),     NA )
  var.superclusters.matrix  <- var.def.ncdf ("superclusters_matrix",  "", list(ox,oy), NA )
  var.merging.matrix        <- var.def.ncdf ("merging_matrix",        "", list(oy,oy), NA )
  var.tree.cutpoints        <- var.def.ncdf ("tree_cutpoints",        "", list(ox),    NA )
  var.cluster.order         <- var.def.ncdf ("cluster_order",         "", list(oy),    NA )

  output.nc <- create.ncdf(output.cdf,list(var.leaves.order,var.new.tree,var.superclusters.matrix,var.merging.matrix,var.ordered.weight.matrix,var.tree.cutpoints,var.cluster.order))

  put.var.ncdf(output.nc,var.leaves.order,comparison$leaves.order)
  put.var.ncdf(output.nc,var.new.tree,comparison$new.tree)
  put.var.ncdf(output.nc,var.superclusters.matrix,comparison$superclusters.matrix)
  put.var.ncdf(output.nc,var.merging.matrix,comparison$merging.matrix)
  put.var.ncdf(output.nc,var.ordered.weight.matrix,comparison$ordered.weight.matrix)
  put.var.ncdf(output.nc,var.tree.cutpoints,as.numeric(rownames(comparison$ordered.weight.matrix)))
  put.var.ncdf(output.nc,var.cluster.order,as.numeric(colnames(comparison$ordered.weight.matrix)))
  
  close.ncdf(output.nc);
  return(output.cdf);
}
